package com.zapi.lottery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zapi.lottery.entity.LotteryWinningNumber;
import com.zapi.lottery.mapper.LotteryWinningNumberMapper;
import com.zapi.lottery.service.LotteryWinningNumberService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 中奖号码配置Service实现类
 * @author: zhonglz
 * @DATE: 2024-06-09
 */
@Service
public class LotteryWinningNumberServiceImpl extends ServiceImpl<LotteryWinningNumberMapper, LotteryWinningNumber> implements LotteryWinningNumberService {

    @Override
    public List<LotteryWinningNumber> getBySettingId(Integer settingId) {
        return this.baseMapper.selectBySettingId(settingId);
    }

    @Override
    public LotteryWinningNumber getByWinningNumber(String winningNumber) {
        return this.baseMapper.selectByWinningNumber(winningNumber);
    }

    @Override
    public List<LotteryWinningNumber> getBySettingIdAndStatus(Integer settingId, Integer status) {
        return this.baseMapper.selectBySettingIdAndStatus(settingId, status);
    }

    @Override
    @Transactional
    public boolean batchSaveWinningNumbers(Integer settingId, List<String> winningNumbers) {
        try {
            // 先删除该奖项下的所有中奖号码配置
            QueryWrapper<LotteryWinningNumber> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("setting_id", settingId);
            this.remove(deleteWrapper);

            // 批量插入新的中奖号码配置
            List<LotteryWinningNumber> lotteryWinningNumbers = new ArrayList<>();
            for (String winningNumber : winningNumbers) {
                LotteryWinningNumber number = new LotteryWinningNumber();
                number.setSettingId(settingId);
                number.setWinningNumber(winningNumber);
                number.setDescription("中奖号码配置");
                number.setStatus(1);
                number.setCreateTime(new Date());
                number.setUpdateTime(new Date());
                lotteryWinningNumbers.add(number);
            }

            return this.saveBatch(lotteryWinningNumbers);
        } catch (Exception e) {
            throw new RuntimeException("批量保存中奖号码配置失败: " + e.getMessage());
        }
    }

    @Override
    public boolean isWinningNumberExists(String winningNumber) {
        QueryWrapper<LotteryWinningNumber> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("winning_number", winningNumber);
        return this.count(queryWrapper) > 0;
    }

    @Override
    public List<LotteryWinningNumber> getAllEnabledWinningNumbers() {
        QueryWrapper<LotteryWinningNumber> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        return this.list(queryWrapper);
    }
} 